package com.example.myapplication;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.GestureDetector;
import android.webkit.WebSettings;
import android.webkit.WebView;
import androidx.appcompat.app.AppCompatActivity;

public class SwipeBackWebViewActivity extends AppCompatActivity {
    private WebView mWebView;
    private GestureDetector mGestureDetector;
    // 边缘检测阈值（屏幕宽度的1/10）
    private int mEdgeThreshold;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swipe_back_webview);
        
        // 初始化WebView
        mWebView = findViewById(R.id.webview);
        initWebViewSettings();
        mWebView.loadUrl("file:///android_asset/h5/index.html"); // 加载本地H5
        
        // 计算边缘阈值
        mEdgeThreshold = getResources().getDisplayMetrics().widthPixels / 10;
        
        // 初始化手势检测器
        mGestureDetector = new GestureDetector(this, new SwipeGestureListener());
        
        // 设置WebView的触摸事件监听
        mWebView.setOnTouchListener((v, event) -> {
            // 先让手势检测器处理事件
            mGestureDetector.onTouchEvent(event);
            // 不消费事件，保证WebView自身的滚动等功能正常
            return false;
        });
    }

    // 初始化WebView设置
    private void initWebViewSettings() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
    }

    // 自定义手势监听器
    private class SwipeGestureListener extends GestureDetector.SimpleOnGestureListener {
        // 滑动距离和速度阈值
        private static final int SWIPE_MIN_DISTANCE = 100;
        private static final int SWIPE_MIN_VELOCITY = 100;

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                // 确保触摸起点在屏幕左侧边缘内
                if (e1.getX() < mEdgeThreshold) {
                    // 计算X轴和Y轴的滑动距离
                    float dx = e2.getX() - e1.getX();
                    float dy = Math.abs(e2.getY() - e1.getY());
                    
                    // 检测向右滑动（满足距离和速度阈值，且水平滑动为主）
                    if (dx > SWIPE_MIN_DISTANCE && velocityX > SWIPE_MIN_VELOCITY && dy < dx / 2) {
                        if (mWebView.canGoBack()) {
                            mWebView.goBack();
                            return true;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        // 允许长按事件等其他手势正常工作
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    }

    @Override
    public void onBackPressed() {
        // 优先使用WebView的返回功能
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        // 销毁WebView，避免内存泄漏
        if (mWebView != null) {
            mWebView.destroy();
        }
        super.onDestroy();
    }
}
